package com.example.demo5072.config;

import org.aspectj.lang.JoinPoint;
import org.aspectj.lang.annotation.AfterReturning;
import org.aspectj.lang.annotation.Aspect;
import org.aspectj.lang.annotation.Before;
import org.aspectj.lang.annotation.Pointcut;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.stereotype.Component;
import org.springframework.web.context.request.RequestContextHolder;
import org.springframework.web.context.request.ServletRequestAttributes;

import javax.servlet.http.HttpServletRequest;
import java.util.Arrays;

/**
 * AOP配置
 */
@Aspect
@Component
public class LogWebAspect {

    private static final Logger logger = LoggerFactory.getLogger(LogWebAspect.class);



    /**
     * @Pointcut 定义一个方法为切点里面的内容为一个表达式
     * 这里记录所有控制器的日志
     */
    @Pointcut("execution(public * com.example.demo5072.controller.*.*(..))")
    public void webLog() {
    }

    /**
     * 使用AOP前置通知拦截请求参数信息
     */
    @Before("webLog()")
    public void doBefore(JoinPoint joinPoint) throws Throwable {


        // 接收到请求，记录请求内容
        logger.info("============AOP统一日志记录=======================");
        ServletRequestAttributes attributes = (ServletRequestAttributes) RequestContextHolder.getRequestAttributes();
        HttpServletRequest request = attributes.getRequest();

        // 记录下请求内容
        logger.info("请求IP : " + request.getRemoteAddr());

        logger.info("请求地址URL : " + request.getRequestURL().toString());

        logger.info("请求方法HTTP_METHOD : " + request.getMethod());

        logger.info("请求参数ARGS : " + Arrays.toString(joinPoint.getArgs()));

        logger.info("对应控制器方法CLASS_METHOD : " + joinPoint.getSignature().getDeclaringTypeName() + "." + joinPoint.getSignature().getName());



    }

    /**
     * 后置通知
     *
     * @param ret
     * @throws Throwable
     */
    @AfterReturning(returning = "ret", pointcut = "webLog()")
    public void doAfterReturning(Object ret) {
        // 处理完请求，返回内容
        logger.info("返回响应的视图名RESPONSE : " + ret );
    }


}
